package com.example.takeaway.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.example.takeaway.entity.AlipayBean;
import com.example.takeaway.entity.Orderdetail;
import com.example.takeaway.entity.Orders;
import com.example.takeaway.serivce.AlipayService;
import com.example.takeaway.serivce.IOrdersService;
import com.example.takeaway.utils.PageResult;
import com.example.takeaway.utils.PassToken;
import com.example.takeaway.utils.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


/**
 * ordersController
 * 
 * @author ruoyi
 * @date 2025-05-15
 */
@RestController
@RequestMapping("/system/orders")
public class OrdersController {
    @Autowired
    private IOrdersService ordersService;

    @Autowired
    AlipayService alipayService;


    /**
     * 查询orders列表
     */
//    @PreAuthorize("@ss.hasPermi('system:orders:list')")
    @GetMapping("/list")
    public ServerResponse list(Orders orders ,@RequestParam(defaultValue = "1") int pageNum, @RequestParam(defaultValue = "10")int pageSize) {
//        startPage();
        PageResult pageResult = ordersService.selectOrdersList(orders,pageNum,pageSize);
//        return getDataTable(list);
        return ServerResponse.createBysuccess(200, pageResult, "查询成功");
    }

    /**
     * 导出orders列表
     */
//    @PreAuthorize("@ss.hasPermi('system:orders:export')")
//    @Log(title = "orders", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(HttpServletResponse response, Orders orders)
//    {
//        List<Orders> list = ordersService.selectOrdersList(orders);
//        ExcelUtil<Orders> util = new ExcelUtil<Orders>(Orders.class);
//        util.exportExcel(response, list, "orders数据");
//    }

    /**
     * 获取orders详细信息
     */
//    @PreAuthorize("@ss.hasPermi('system:orders:query')")
    @GetMapping(value = "/{orderid}")
    public ServerResponse getInfo(@PathVariable("orderid") Long orderid) {
        Orders orders = ordersService.selectOrdersByOrderid(orderid);
        return ServerResponse.createBysuccess(200, orders, "查询成功");

    }


    @PassToken
    @GetMapping(value = "/getOrders/{ordersn}")
    public ServerResponse getOrders(@PathVariable("ordersn") String ordersn) {
        return ServerResponse.createBysuccess(200, ordersService.getOrdersByOrdersn(ordersn), "获取成功");

    }

    /**
     * 新增orders
     */
//    @PreAuthorize("@ss.hasPermi('system:orders:add')")
//    @Log(title = "orders", businessType = BusinessType.INSERT)
    @PostMapping
    public ServerResponse add(@RequestBody Orders orders) {
        orders.setCreatetime(new Date());
        System.out.println(orders.getOrdersn());
        String ordersn = UUID.randomUUID() + "";           // System.currentTimeMillis();  // 20250508+(Math.random()*100000)
        orders.setOrdersn(ordersn);  //订单编号是随机产生的，前端产生可以，后端也可以产生
        List<Orderdetail> list = orders.getOrderdetailsList();
        System.out.println(list);
        if (list == null) {
            System.out.println("获取不到");
        }
        for (Orderdetail od : list) {
            od.setOrdersn(ordersn);
        }

        System.out.println(orders.getOrdersn());
        System.out.println(orders.getOrderdetailsList().size());
        int i = ordersService.insertOrders(orders);
        if (i > 0) {
            return ServerResponse.createBysuccess(200, ordersn, "添加成功");
        } else {
            return ServerResponse.createByfail(500, "添加失败");
        }
    }

    /**
     * 修改orders
     */
//    @PreAuthorize("@ss.hasPermi('system:orders:edit')")
//    @Log(title = "orders", businessType = BusinessType.UPDATE)
    @PutMapping
    public ServerResponse edit(@RequestBody Orders orders) {
        int i = ordersService.updateOrders(orders);
        if (i > 0) {
            return ServerResponse.createBysuccess(200, "", "新增成功");
        } else {
            return ServerResponse.createByfail(400, "新增失败");
        }
    }

    /**
     * 删除orders
     */
//    @PreAuthorize("@ss.hasPermi('system:orders:remove')")
//    @Log(title = "orders", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orderids}")
    public ServerResponse remove(@PathVariable Long[] orderids) {
        int i = ordersService.deleteOrdersByOrderids(orderids);
        if (i > 0) {
            return ServerResponse.createBysuccess(200, "", "新增成功");
        } else {
            return ServerResponse.createByfail(400, "新增失败");
        }
    }


    @PassToken
    @GetMapping("/pay")
    public String payOrders(String outTradeNo, String subject, String totalAmount, String body, HttpServletRequest response) throws AlipayApiException {
        System.out.println(123);
        System.out.println(outTradeNo + "............");
        AlipayBean alipayBean = new AlipayBean();
        alipayBean.setOut_trade_no(outTradeNo);
        alipayBean.setSubject(subject);
        alipayBean.setTotal_amount(totalAmount);
        alipayBean.setBody(body);
        // String s =alipayService.aliPay(alipayBean);
        //  return ResponseResult.createBySuccess(200, s, "返回数据成功");
        return alipayService.alipay(alipayBean);
    }


    @PassToken
    @GetMapping("/alipay_back")
    public String alipayback(@RequestParam Map<String, String> params, HttpServletRequest request) {
        //订单号
        String orderNo = params.get("out_trade_no");   //很重要
        //支付宝的交易号
        String tradeNo = params.get("trade_no");
        //支付宝的交易状态
        String tradeStatus = params.get("trade_status");
        System.out.println(orderNo + "         " + tradeNo + "          " + tradeStatus);
        //  Orders o = new Orders();
        // o.setOrdersn(orderNo);
        // Orders order = ordersService.selectOrdersList(o,1,1).getRows().get(0);
        Orders order = ordersService.getOrdersByOrdersn(orderNo);  //根据ordersn获取Orders对象
        if (order != null) {
            order.setState(new Long(1));
            int i = ordersService.updateOrders(order);  //更新订单的状态
            System.out.println(i + "     ");
            //商品的库存的修改

        }
        return "支付成功";
    }
}
